<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            display: flex;
            justify-content: center;
            align-items: center;
            overflow: hidden;
            min-height: 100vh;
            gap: 4vh;
            background-color: #122;
        }

        button {
            text-align: center;
            padding: 4vmin 8vmin;
            border: none;
            border-radius: 10vmin;
            color: #fff;
            font-size: 26px;
            letter-spacing: 4px;
            background-image: linear-gradient(to right, #8acffe, #495aff);
            cursor: pointer;
            position: relative;
            overflow: hidden;
        }

        button:nth-child(2) {
            background-image: linear-gradient(to right, #ed6ea0, #ec8c69);
        }

        button span {
            background-color: #fff;
            border-radius: 50%;
            position: absolute;
            transform: translate(-50%, -50%);
            /* 只执行一次动画 */
            animation: animate 1s ease-out 1;
            /* 避免波纹元素对事件干扰 */
            pointer-events: none;
        }

        /* 从0扩大到圆且透明度逐渐降低直至消失 */
        @keyframes animate {
            0% {
                width: 0;
                height: 0;
                opacity: .5;
            }

            100% {
                width: 100vmin;
                height: 100vmin;
                opacity: 0;
            }
        }
    </style>
</head>

<body>
    <button>
        按钮
    </button>
    <button>
        水波纹
    </button>
    <script>
        const buttons = document.querySelectorAll('button')
        buttons.forEach((button) => {
            button.addEventListener('click', (e) => {
                // clientx是 鼠标 相对于浏览器边缘的距离
                // target.offsetLeft是 被点击元素 相对于浏览器边缘的距离
                // x是鼠标相对于被点击元素左上角的距离
                let x = e.clientX - e.target.offsetLeft
                let y = e.clientY - e.target.offsetTop

                let ripples = document.createElement("span")
                ripples.style.left = x + 'px'
                ripples.style.top = y + 'px'

                button.appendChild(ripples)

                // 定时删除元素 提升性能
                setTimeout(() => {
                    ripples.remove()
                }, 1200)
            })
        })
    </script>
</body>

</html>